package me.zhengjie.modules.website.service.impl;

import me.zhengjie.modules.website.domain.Topiccontent;
import me.zhengjie.modules.website.repository.TopiccontentRepository;
import me.zhengjie.modules.website.repository.TopiccontentSpecifications;
import me.zhengjie.modules.website.repository.TopicsSpecifications;
import me.zhengjie.modules.website.service.TopiccontentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import me.zhengjie.modules.website.domain.PageResult;

import java.util.List;

/**
 * @author system
 * @since 2024-12-12 11:42:51
 */
@Service
public class TopiccontentServiceImpl implements TopiccontentService {

    @Autowired
    private TopiccontentRepository topiccontentRepository;

    @Override
    public PageResult<Topiccontent> findPage(Topiccontent topiccontent, Pageable pageable) {
        // 创建带排序的 Pageable，按 updateTime 降序排序
        Pageable sortedPageable = PageRequest.of(
                pageable.getPageNumber(),
                pageable.getPageSize(),
                Sort.by(Sort.Direction.ASC, "sortOrder")
        );

        // 使用带排序的 Pageable 进行查询
        Page<Topiccontent> page = topiccontentRepository.findAll(TopiccontentSpecifications.queryList(topiccontent), sortedPageable);

        // 构建分页结果
        PageResult<Topiccontent> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }


    @Override
    public List<Topiccontent> findList(Topiccontent topiccontent) {
        return topiccontentRepository.findAll(
                TopiccontentSpecifications.queryList(topiccontent),
                Sort.by(Sort.Direction.ASC, "sortOrder")
        );
    }

    @Override
    public Topiccontent findById(Long id) {
        return topiccontentRepository.findById(id).orElse(null);
    }

    @Override
    public Topiccontent insert(Topiccontent topiccontent) {
        return topiccontentRepository.save(topiccontent);
    }

    @Override
    public Topiccontent update(Topiccontent topiccontent) {
        return topiccontentRepository.saveAndFlush(topiccontent);
    }

    @Override
    public void delete(Long id) {
        topiccontentRepository.deleteById(id);
    }

}